package logic

import (
	"context"
	"fmt"
	"jd.com-user-system/models/mysql"

	"jd.com-user-system/userrpc/internal/svc"
	"jd.com-user-system/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *userrpc.UserLoginRequest) (*userrpc.UserLoginResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User

	err := mysql.Db.Debug().Where("username = ?", in.Username).Find(&user).Error
	if err != nil {
		return nil, err
	}
	if user.ID == 0 {
		return nil, fmt.Errorf("用户名不存在")
	}
	if user.Password != in.Password {
		return nil, fmt.Errorf("密码错误")
	}

	return &userrpc.UserLoginResponse{Id: int64(user.ID)}, nil
}
